<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 
 * @author liubin-bt
 * @property Attach_model $Attach_model
 * @property Project_model $Project_model
 * @property ProjectFollows_model $ProjectFollows_model
 * @property ProjectAttach_model $ProjectAttach_model
 * @property ProjectMarketCom_model $ProjectMarketCom_model
 * @property ProjectRoadShow_model $ProjectRoadShow_model
 * @property ProjectDeliveryAgree_model $ProjectDeliveryAgree_model
 * @property InvestInstitution_model $InvestInstitution_model
 * @property ProjectInvestorRecom_model $ProjectInvestorRecom_model
 * @property Investor_model $Investor_model
 */
class Project extends Base {

    public function __construct(){
        parent::__construct();
        $this->load->model('Project_model');
    }

    public function getSelectData(){
        include_once APPPATH."config/projectstatus.php";
        $this->outJsonData(0, $config);
    }

    public function pageList(){
        $this->config->load('projectstatus');
        $this->load->model('ProjectFollows_model');
        $page = intval($this->getSafeRequest('page', 1));
        $type = intval($this->getSafeRequest('type', 0));
        $project_name = $this->getSafeRequest('project_name', '');
        list($count, $list) = $this->Project_model->gePageList($project_name, $type, $page);
        /* if( $list ){
            $ids = array_column($list, 'id');
            $users = $this->ProjectFollows_model->getUserByProjectIds($ids);
            foreach ($list as &$v){
                $v['members'] = '';
                $umembers = isset($users[$v['id']]) ? $users[$v['id']] : [];
                if( $umembers ){
                    $user_name = implode(',', array_column($umembers, 'user_name'));
                    $v['members'] = $user_name; 
                }
            }
        } */
        $project_source_config = $this->config->item('project_source');
        $project_push_status_config = $this->config->item('project_push_status');
        $finance_rotation_config = $this->config->item('finance_rotation');
        foreach ($list as &$v){
            $v['project_first_time'] = date('Y-m-d H:i:s', $v['project_first_time']);
            $v['project_revisit_time'] = date('Y-m-d H:i:s', $v['project_revisit_time']);
            $v['company_area'] = json_decode($v['company_area'], true);
            $v['project_cover'] = !empty($v['project_cover']) ? json_decode($v['project_cover'], true) : [];
            $v['project_team'] = json_decode($v['project_team'], true);
            $v['finance_rotation'] = !empty($finance_rotation_config[$v['finance_rotation']]) ? $finance_rotation_config[$v['finance_rotation']] : '';
            $v['finance_history'] = json_decode($v['finance_history'], true);
            $v['project_source'] = isset($project_source_config[$v['project_source']]) ? $project_source_config[$v['project_source']] : '';
            $v['project_push_status'] = isset($project_push_status_config[$v['project_push_status']]) ? $project_push_status_config[$v['project_push_status']] : '';
        }
        $this->outJsonData(1, ['count'=>$count, 'list'=>$list]);
    }
    /**
     * 添加基本信息
     */
    public function addBaseInfo(){
        $postdata = file_get_contents('php://input');
        if( $postdata ){
            $_POST = json_decode($postdata, true);
        }
        $this->load->model('ProjectAttach_model');
        if( $_POST ){
            $project_id = $this->getSafePost('id', 0);
            $data['project_name'] = $this->getSafePost('project_name', '');
            $data['company_name'] = $this->getSafePost('company_name', '');
            $data['company_legal'] = $this->getSafePost('company_legal', '');
            $data['company_regaddr'] = $this->getSafePost('company_regaddr', '');
            $data['company_url'] = $this->getSafePost('company_url', '');
            $company_area = isset($_POST['company_area']) ? $_POST['company_area'] : [];
            $company_area = array_filter($company_area, 'intval');
            $data['company_area'] = json_encode($company_area);
            $data['company_addr'] = $this->getSafePost('company_addr', '');
            $data['company_industry'] = $this->getSafePost('company_industry', '');
            $data['project_source'] = intval($this->getSafePost('project_source', ''));
            $data['project_mark'] = $this->getSafePost('project_mark', '');
            $data['project_creator'] = $this->getSafePost('project_creator', '');
            $data['project_push_status'] = intval($this->getSafePost('project_push_status', ''));
            $data['project_first_time'] = strtotime($this->getSafePost('project_first_time', ''));
            $data['project_revisit_time'] = strtotime($this->getSafePost('project_revisit_time', ''));
            $data['company_desc'] = $this->getSafePost('company_desc', '');
            $data['project_desc'] = $this->getSafePost('project_desc', '');
            $data['company_bussiness'] = $this->getSafePost('company_bussiness', '');
            $data['finance_rotation'] = intval($this->getSafePost('finance_rotation', ''));
            $data['finance_expect'] = $this->getSafePost('finance_expect', '');
            $project_team = isset($_POST['project_team']) ? $_POST['project_team'] : [];
            $data['project_team'] = json_encode($project_team);
            $project_cover = isset($_POST['project_cover']) ? $_POST['project_cover'] : [];
            $data['project_cover'] = json_encode($project_cover);
            $finance_history = isset($_POST['finance_history']) ? $_POST['finance_history'] : [];
            $data['finance_history'] = json_encode($finance_history);
            $files_bp = isset($_POST['files_bp']) ? $_POST['files_bp'] : [];
            $data['files_bp'] = json_encode($files_bp);
            $files_pitchbook = isset($_POST['files_pitchbook']) ? $_POST['files_pitchbook'] : [];
            $data['files_pitchbook'] = json_encode($files_pitchbook);
            if( !$project_id ){
                //add
                $data['uid'] = $this->uid;
                $data['ctime'] = $_SERVER['REQUEST_TIME'];
                $project_id = $this->Project_model->insert($data);
                $this->outJsonData(0, '添加成功');
            } else {
                //edit
                $res = $this->Project_model->update(['id'=>$project_id], $data);
                $this->outJsonData(0, '编辑成功');
            }
        } else {
            //get
            $project_id = $this->getSafeRequest('id', 0);
            if( !$project_id ){
                $this->outJsonData(-1, '项目id不能为空');
            }
            $project = $this->Project_model->getProjectOne($project_id);
            if( $project ){
                $project['project_first_time'] = date('Y-m-d H:i:s', $project['project_first_time']);
                $project['project_revisit_time'] = date('Y-m-d H:i:s', $project['project_revisit_time']);
                $project['start_time'] = !empty($project['start_time']) ? date('Y-m-d H:i:s', $project['start_time']) : '';
                $project['company_area'] = json_decode($project['company_area'], true);
                $project['project_team'] = json_decode($project['project_team'], true);
                $project['project_cover'] = !empty($project['project_cover']) ? json_decode($project['project_cover'], true) : [];
                $project['finance_rotation'] = !empty($project['finance_rotation']) ? $project['finance_rotation'] : '';
                $finance_history = json_decode($project['finance_history'], true);
                $files_bp = json_decode($project['files_bp'], true);
                $files_pitchbook = json_decode($project['files_pitchbook'], true);
                $project['finance_history'] = $finance_history;
                $project['files_bp'] = $files_bp;
                $project['files_pitchbook'] = $files_pitchbook;
                $project['up_feedback_time'] = !empty($project['up_feedback_time']) ? $project['up_feedback_time'] : date('Y-m-d H:i:s', $project['ctime']);
                $project['isadmin'] = 0;
                if( $this->auth_invaid($project_id) ){
                    $project['isadmin'] = 1;
                }
            } else {
                $this->outJsonData(-1, '该项目不存在');
            }
            
            $this->outJsonData(0, $project);
        }
    }
    
    /**
     * 权限管理
     */
    public function authManage(){
        $postdata = file_get_contents('php://input');
        if( $postdata ){
            $_POST = json_decode($postdata, true);
        }
        $id = intval($this->getSafeRequest('id'));
        $this->load->model('ProjectFollows_model');
        if( !$this->auth_invaid($id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        if( $_POST ){
            $uids = isset($_POST['members']) ? $_POST['members'] : [];
            if( !is_array($uids) && empty($uids) ){
                $uids = [];
            } else {
                $uids = array_filter($uids);
                $uids = array_filter($uids, 'intval');
            }
            $data['manager'] = $this->getSafePost('manager', '');
            $data['is_start'] = intval($this->getSafePost('is_start', 0));
            $data['start_time'] = strtotime($this->getSafePost('start_time', ''));
            $data['execute_status'] = intval($this->getSafePost('execute_status', ''));
            if( $id ){
                $this->Project_model->update(['id'=>$id], $data);
            }
            //更新项目组成员
            $this->ProjectFollows_model->updateBatch($id, $uids);
            
            $this->outJsonData(0, '操作成功');
        } else {
            $project = $this->Project_model->getProjectOne($id, 'manager,is_start,start_time,execute_status');
            if( !$project ){
                $this->outJsonData(-1, '该项目不存在');
            }
            $uids = $this->ProjectFollows_model->getUidsByProjectId($id);
            $project['is_start'] = $project['is_start'] ? true : false;
            $project['execute_status'] = !empty($project['execute_status']) ? $project['execute_status'] : '';
            $project['start_time'] = date('Y-m-d H:i:s', $project['start_time']);
            $project['members'] = $uids;
            $this->outJsonData(0, $project);
        }
    }
    
    /**
     * 市场竞争
     */
    public function marketCom(){
        $postdata = file_get_contents('php://input');
        if( $postdata ){
            $_POST = json_decode($postdata, true);
        }
        $id = intval($this->getSafeRequest('project_id'));
        if( !$this->auth_invaid($id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        $this->load->model('ProjectAttach_model');
        $this->load->model('ProjectMarketCom_model');
        $dbinfo = $this->ProjectMarketCom_model->getInfoByProjectId($id);
        if( $_POST ){
            $data['research'] = $this->getSafePost('research', '');
            $data['abroad'] = json_encode($_POST['abroad']);
            $data['domestic'] = json_encode($_POST['domestic']);
            $data['ctime'] = $_SERVER['REQUEST_TIME'];
            //更新附件
            $files_market= isset($_POST['files_market']) ? $_POST['files_market'] : [];
            $data['files_market'] = json_encode($files_market);
            if( $dbinfo ){
                $this->ProjectMarketCom_model->update(['project_id'=>$id], $data);
            } else {
                $data['project_id'] = $id;
                $this->ProjectMarketCom_model->insert($data);
            }
            $this->outJsonData(0, '操作成功');
        } else {
            if( $dbinfo ){
                unset($dbinfo['id']);
                $dbinfo['files_market'] = json_decode($dbinfo['files_market'], true);
                $dbinfo['abroad'] = json_decode($dbinfo['abroad'], true);
                $dbinfo['domestic'] = json_decode($dbinfo['domestic'], true);
            }
            $this->outJsonData(0, $dbinfo);
        }
    }
    
    /**
     * 路演材料
     */
    public function roadShow(){
        $postdata = file_get_contents('php://input');
        if( $postdata ){
            $_POST = json_decode($postdata, true);
        }
        $id = intval($this->getSafeRequest('project_id'));
        if( !$this->auth_invaid($id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        $this->load->model('ProjectRoadShow_model');
        $dbinfo = $this->ProjectRoadShow_model->getInfoByProjectId($id);
        if( $_POST ){
            $data['wx_data'] = $this->getSafePost('wx_data', '');
            $files_taser = isset($_POST['files_taser']) ? $_POST['files_taser'] : [];
            $data['files_taser'] = json_encode($files_taser);
            $files_bp = isset($_POST['files_bp']) ? $_POST['files_bp'] : [];
            $data['files_bp'] = json_encode($files_bp);
            $files_datapack = isset($_POST['files_datapack']) ? $_POST['files_datapack'] : [];
            $data['files_datapack'] = json_encode($files_datapack);
            $files_fm = isset($_POST['files_fm']) ? $_POST['files_fm'] : [];
            $data['files_fm'] = json_encode($files_fm);
            $files_captable = isset($_POST['files_captable']) ? $_POST['files_captable'] : [];
            $data['files_captable'] = json_encode($files_captable);
            $data['project_log'] = $this->getSafePost('project_log', '');
            //更新附件
            if( $dbinfo ){
                $this->ProjectRoadShow_model->update(['project_id'=>$id], $data);
            } else {
                $data['project_id'] = $id;
                $this->ProjectRoadShow_model->insert($data);
            }
            $this->outJsonData(0, '操作成功');
        } else {
            if( $dbinfo ){
                unset($dbinfo['id']);
                $dbinfo['files_taser'] = json_decode($dbinfo['files_taser'], true);
                $dbinfo['files_bp'] = json_decode($dbinfo['files_bp'], true);
                $dbinfo['files_datapack'] = json_decode($dbinfo['files_datapack'], true);
                $dbinfo['files_fm'] = json_decode($dbinfo['files_fm'], true);
                $dbinfo['files_captable'] = json_decode($dbinfo['files_captable'], true);
            }
            $this->outJsonData(0, $dbinfo);
        }
        
    }
    
    /**
     * 投资人推荐列表
     */
    public function investorPageList(){
        $page = intval($this->getSafeRequest('page', 1));
        $project_id = intval($this->getSafeRequest('project_id'));
        if( !$this->auth_invaid($project_id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        $this->load->model('ProjectInvestorRecom_model');
        list($count, $list) = $this->ProjectInvestorRecom_model->gePageList($project_id, $page);
        foreach( $list as &$v ){
            $v['status'] = !empty($v['status']) ? $v['status'] : '';
        }
        $this->outJsonData(0, ['count'=>$count, 'list'=>$list]);
    }
    /**
     * 添加机构
     */
    public function addIns(){
        $postdata = file_get_contents('php://input');
        if( $postdata ){
            $_POST = json_decode($postdata, true);
        }
        $project_id = intval($this->getSafePost('project_id'));
        if( !$this->auth_invaid($project_id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        $ids = !empty($_POST['ids']) ? $_POST['ids'] : [];
        if( !is_array($ids) ){
            $this->outJsonData(-1, 'ids格式错误');
        }
        $ids = array_filter($ids);
        $ids = array_filter($ids, 'intval');
        if( !$ids ){
            $this->outJsonData(-1, 'ids不能为空');
        }
        $this->load->model('ProjectInvestorRecom_model');
        $this->load->model('Investor_model');
        $data = [];
        foreach ($ids as $investor_id){
            //重复添加
            $exsit = $this->ProjectInvestorRecom_model->getByInvestorId($investor_id);
            if( $exsit ){
                continue;
            }
            $data[] = [
                'project_id' => $project_id,
                'investor_id' => $investor_id,
                'status'=>1
            ];
        }
        if( $data ){
            $this->ProjectInvestorRecom_model->insert_batch($data);
        }
        $this->outJsonData(0, '添加成功');
    }
    
    /**
     * 编辑投资人状态
     */
    public function updateIns(){
        $postdata = file_get_contents('php://input');
        if( $postdata ){
            $_POST = json_decode($postdata, true);
        }
        $project_id = intval($this->getSafeRequest('project_id'));
        if( !$this->auth_invaid($project_id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        $id = intval($this->getSafeRequest('id'));
        if( !$id ){
            $this->outJsonData(-1, 'id不能为空');
        }
        $status = $this->getSafePost('status', '');
        $this->load->model('ProjectInvestorRecom_model');
        $this->ProjectInvestorRecom_model->update(['investor_id'=>$id, 'project_id'=>$project_id], ['status'=>$status]);
        
        $this->outJsonData(0, '操作成功');
    }
    
    public function deleteIns(){
        $project_id = intval($this->getSafeRequest('project_id'));
        if( !$this->auth_invaid($project_id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        $id = intval($this->getSafeRequest('id'));
        if( !$id ){
            $this->outJsonData(-1, 'id不能为空');
        }
        $this->load->model('ProjectInvestorRecom_model');
        $this->ProjectInvestorRecom_model->delete(['investor_id'=>$id, 'project_id'=>$project_id]);
        
        $this->outJsonData(0, '删除成功');
    }

    /**
     * 反馈管理
     */
    public function feedBack(){
        $postdata = file_get_contents('php://input');
        if( $postdata ){
            $_POST = json_decode($postdata, true);
        }
        $project_id = intval($this->getSafeRequest('project_id'));
        if( !$this->auth_invaid($project_id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        $this->load->model('ProjectInvestorRecom_model');
        list($count, $list) = $this->ProjectInvestorRecom_model->gePageList($project_id, 1, 1000);
        
        $this->config->load('projectstatus');
        $recomm_status = $this->config->item('recomm_status');
        //列表分组
        $grouplist['recomm_count'] = [];
        $grouplist['meeting_count'] = [];
        $grouplist['roadshow_count'] = [];
        $countlist = [];
        $fbcount = [];
        foreach ($list as $v){
            $temp = ['id' => $v['id'],
                'instustry_name' => $v['instustry_name'],
                'job' => $v['job'],
                'investor' => $v['investor'],
                'next' => $v['next'],
                'addr' => $v['addr'],
                'status_name'=>isset($recomm_status[$v['status']]) ? $recomm_status[$v['status']] : ''
            ];
            $countlist[$v['status']][] = $temp;
            $fbcount[$v['fb_status']][] = $temp;
            if( in_array($v['status'], ['1','2','3','4']) ){
                $grouplist['recomm_list'][] = $temp;
            } else if( in_array($v['status'], ['5','6','7']) ){
                $grouplist['meeting_list'][] = $temp;
            } else {
                $temp['fb_status'] = !empty($v['fb_status']) ? $v['fb_status'] : '';
                $grouplist['roadshow_list'][] = $temp;
            }
        }
        $fb_status = $this->config->item('fb_status');
        $grouplist['recomm_count'] = [
            ['status_name'=>$recomm_status['1'],'count'=>isset($countlist['1']) ? count($countlist['1']) : 0],
            ['status_name'=>$recomm_status['2'], 'count'=>isset($countlist['2']) ? count($countlist['2']) : 0],
            ['status_name'=>$recomm_status['3'], 'count'=>isset($countlist['3']) ? count($countlist['3']) : 0],
            ['status_name'=>$recomm_status['4'], 'count'=>isset($countlist['4']) ? count($countlist['4']) : 0]
        ];
        $grouplist['meeting_count'] = [
            ['status_name'=>$recomm_status['5'],'count'=>isset($countlist['5']) ? count($countlist['5']) : 0],
            ['status_name'=>$recomm_status['6'], 'count'=>isset($countlist['6']) ? count($countlist['6']) : 0],
            ['status_name'=>$recomm_status['7'], 'count'=>isset($countlist['7']) ? count($countlist['7']) : 0],
        ];
        $roadshowcount = [];
        foreach ($fb_status as $fk=>$fv){
            $roadshowcount[] = ['status_name'=>$fv,'count'=>isset($fbcount[$fk]) ? count($fbcount[$fk]) : 0];
        }
        $grouplist['roadshow_count'] = $roadshowcount;
        
        $this->outJsonData(0, $grouplist);
    }
    
    /**
     * 编辑反馈
     */
    public function updateFeedBack(){
        $postdata = file_get_contents('php://input');
        if( $postdata ){
            $_POST = json_decode($postdata, true);
        }
        $project_id = intval($this->getSafeRequest('project_id'));
        if( !$this->auth_invaid($project_id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        $id = intval($this->getSafeRequest('id'));
        if( !$id ){
            $this->outJsonData(-1, 'id不能为空');
        }
        $next = $this->getSafePost('next', '');
        $addr = $this->getSafePost('addr', '');
        $this->load->model('ProjectInvestorRecom_model');
        $this->ProjectInvestorRecom_model->update(['investor_id'=>$id, 'project_id'=>$project_id], ['next'=>$next, 'addr'=>$addr]);
        
        $this->load->model('Project_model');
        $this->Project_model->update(['id'=>$project_id], ['up_feedback_time'=>date('Y-m-d H:i:s')]);
        
        $this->outJsonData(0, '操作成功');
    }
    
    public function upFeedBackStatus(){
        $postdata = file_get_contents('php://input');
        if( $postdata ){
            $_POST = json_decode($postdata, true);
        }
        $project_id = intval($this->getSafeRequest('project_id'));
        if( !$this->auth_invaid($project_id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        $id = intval($this->getSafeRequest('id'));
        if( !$id ){
            $this->outJsonData(-1, 'id不能为空');
        }
        $fb_status = intval($this->getSafePost('fb_status', ''));
        $this->load->model('ProjectInvestorRecom_model');
        $this->ProjectInvestorRecom_model->update(['investor_id'=>$id, 'project_id'=>$project_id], ['fb_status'=>$fb_status]);
    
        $this->load->model('Project_model');
        $this->Project_model->update(['id'=>$project_id], ['up_feedback_time'=>date('Y-m-d H:i:s')]);
    
        $this->outJsonData(0, '操作成功');
    }
    
    /**
     * 交割协议
     */
    public function deliveryAgree(){
        $postdata = file_get_contents('php://input');
        if( $postdata ){
            $_POST = json_decode($postdata, true);
        }
        $id = intval($this->getSafeRequest('project_id'));
        if( !$this->auth_invaid($id) ){
            $this->outJsonData(-1, '您没有权限进行该操作');
        }
        $this->load->model('ProjectDeliveryAgree_model');
        $dbinfo = $this->ProjectDeliveryAgree_model->getInfoByProjectId($id);
        if( $_POST ){
            $files_nda = isset($_POST['files_nda']) ? $_POST['files_nda'] : [];
            $data['files_nda'] = json_encode($files_nda);
            $files_ts = isset($_POST['files_ts']) ? $_POST['files_ts'] : [];
            $data['files_ts'] = json_encode($files_ts);
            $files_spa = isset($_POST['files_spa']) ? $_POST['files_spa'] : [];
            $data['files_spa'] = json_encode($files_spa);
            $files_sha = isset($_POST['files_sha']) ? $_POST['files_sha'] : [];
            $data['files_sha'] = json_encode($files_sha);
            //更新附件
            if( $dbinfo ){
                $this->ProjectDeliveryAgree_model->update(['project_id'=>$id], $data);
            } else {
                $data['project_id'] = $id;
                $this->ProjectDeliveryAgree_model->insert($data);
            }
            $this->outJsonData(0, '操作成功');
        } else {
            if( $dbinfo ){
                unset($dbinfo['id']);
                $dbinfo['files_nda'] = json_decode($dbinfo['files_nda'], true);
                $dbinfo['files_ts'] = json_decode($dbinfo['files_ts'], true);
                $dbinfo['files_spa'] = json_decode($dbinfo['files_spa'], true);
                $dbinfo['files_sha'] = json_decode($dbinfo['files_sha'], true);
            }
            $this->outJsonData(0, $dbinfo);
        }
    }
    
    private function saveProjectAttach($project_id, $field, $ids, $action='add'){
        $this->load->model('Attach_model');
        if( $action == 'edit'){
            $exsitfiles = $this->ProjectAttach_model->getAttachList($project_id, $field);
            if( !empty($exsitfiles[$field]) ){
                $exsit_ids = array_column($exsitfiles[$field], 'attach_id');
                $del_ids = array_diff($exsit_ids, $ids);
                if( $del_ids ){
                    $this->ProjectAttach_model->delete_attach_in($del_ids);
                }
                $ids = array_diff($ids, $exsit_ids);
            }
        }
        if( !$ids ){
            return;
        }
        $files = $this->Attach_model->getListByIds($ids);
        $insertdb = [];
        foreach ($files as $v){
            $insertdb[] = [
                'attach_id'=>$v['id'],
                'project_id'=>$project_id,
                'field'=>$field,
                'filename'=>$v['filename'],
                'url'=>$v['url'],
                'size'=>$v['size'],
                'ext'=>$v['ext']
            ];
        }
        $res = $this->ProjectAttach_model->insertBatch($insertdb);
        return $res;
    }
}
?>